//
//  CFAsmanFileManager.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 10/14/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import UIKit
import AVFoundation

class CFAsmanFileManager: NSObject {
  
  static func startExportVideoWithVideoAsset(asset:AVAsset,fileName:String,complete:@escaping (_ fileName:String,_ outputPath:String?)->()){
    let presets = AVAssetExportSession.exportPresets(compatibleWith: asset)
    var pre:String = AVAssetExportPreset640x480
    if presets.contains(AVAssetExportPreset3840x2160) {
      pre = AVAssetExportPreset1920x1080
    }else if presets.contains(AVAssetExportPreset1920x1080){
      pre = AVAssetExportPreset1920x1080
    }else if presets.contains(AVAssetExportPreset1280x720){
      pre = AVAssetExportPreset1280x720
    }else if presets.contains(AVAssetExportPreset960x540){
      pre = AVAssetExportPreset960x540
    }
    let session = AVAssetExportSession(asset: asset, presetName: pre)
    let outputPath = NSTemporaryDirectory().appending("\(fileName).mp4")
    print(outputPath);
    session?.outputURL = URL(fileURLWithPath: outputPath)
    session?.shouldOptimizeForNetworkUse = true
    let supportedTypeArr = session?.supportedFileTypes ?? []
    if supportedTypeArr.count >= 1 {
      session?.outputFileType = supportedTypeArr.first
    }else{
      print("视频类型暂不支持导出")
      complete(fileName,nil)
      return
    }
//    if supportedTypeArr.contains(.mp4) {
//      session?.outputFileType = .mp4
//    }else if supportedTypeArr.count == 0 {
//      print("视频类型暂不支持导出")
//      complete(fileName,nil)
//      return
//    }else{
//      session?.outputFileType = supportedTypeArr.first
//    }
    session?.exportAsynchronously(completionHandler: {
      guard let `session` = session else {
        complete(fileName,nil)
        return
      }
      switch session.status {
      case .unknown:
          print("export file unknow staus")
      case .waiting:
        print("export file waiting staus")
      case .exporting:
        print("export file unknow staus")
      case .completed:
        DispatchQueue.main.async {
            complete(fileName,session.outputURL?.path)
        }
      case .failed:
        print("export file failed staus")
        complete(fileName,nil)
        return
      case .cancelled:
        print("export file cancelled staus")
        complete(fileName,nil)
//        return
      @unknown default:break
      }
    })
  }
}
